﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Data.Common;
using Spring.Data.Generic;
using System.Reflection;
using System.Data;

namespace Infrastructure
{
    public static class DBHelper
    {
        private static object s_initializeLock = new object();

        public static AdoTemplate SpringDBTemplate { get; private set; }

        public static void CreateSpringDBConn(string conn, string dbProvider)
        {
            lock (s_initializeLock)
            {
                if (SpringDBTemplate == null)
                {
                    IDbProvider provider = DbProviderFactory.GetDbProvider(dbProvider);
                    provider.ConnectionString = conn;
                    SpringDBTemplate = new AdoTemplate(provider);
                }
            }
        }

        public static void CreateAdoNetDBConn(string conn)
        { 
            
        }

        public static void CreateMangoDBConn(string conn)
        { 
        
        }

        public static void CreateObj<T>(T obj, string strSql)
        {
            IDbParameters para = DBHelper.SpringDBTemplate.CreateDbParameters();
            PropertyInfo[] infos = obj.GetType().GetProperties();

            foreach (var item in infos)
                para.Add(item.Name, (DbType)Enum.Parse(typeof(DbType), item.PropertyType.Name)).Value = item.GetValue(obj, null);

            DBHelper.SpringDBTemplate.ExecuteScalar(CommandType.Text, strSql, para);
        }
    }
}
